package com.selfstudy.service.impl;

import com.selfstudy.context.BaseContext;
import com.selfstudy.exception.AccountNotFoundException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.selfstudy.constant.JwtClaimsConstant;
import com.selfstudy.constant.StatusConstant;
import com.selfstudy.dto.StudentUserLoginDTO;
import com.selfstudy.dto.StudentUserRegisterDTO;
import com.selfstudy.entity.StudentUser;
import com.selfstudy.exception.AccountLockedException;
import com.selfstudy.exception.PasswordErrorException;
import com.selfstudy.mapper.StudentUserMapper;
import com.selfstudy.properties.JwtProperties;
import com.selfstudy.service.IStudentUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.selfstudy.utils.JwtUtil;
import com.selfstudy.vo.StudentUserInfoVO;
import com.selfstudy.vo.StudentUserLoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 学生用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-04-08
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class StudentUserServiceImpl extends ServiceImpl<StudentUserMapper, StudentUser> implements IStudentUserService {
    private final JwtProperties jwtProperties;

    @Transactional
    public StudentUserLoginVO login(StudentUserLoginDTO studentUserLoginDTO){
        String username = studentUserLoginDTO.getUsername();
        String password = studentUserLoginDTO.getPassword();
        // 1. 校验用户名和密码是否为空
        if (username == null || password == null) {
            throw new AccountNotFoundException("用户名或密码不能为空");
        }
        // 2. 查询用户信息
        StudentUser user = baseMapper.selectOne(new QueryWrapper<StudentUser>()
                .eq("username", username));
        // 3. 检查用户是否存在
        if (Objects.isNull(user)) {
            throw new AccountNotFoundException("用户不存在");
        }
        // 4. 验证密码是否正确（假设密码存储为 MD5 哈希值）
        String hashedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!hashedPassword.equals(user.getPassword())) {
            throw new PasswordErrorException("密码错误");
        }
        // 5. 检查账户是否被锁定
        if (StatusConstant.DISABLE.equals(user.getStatus())) {
            throw new AccountLockedException("账户已被锁定");
        }
        user.setLastLoginTime(LocalDateTime.now());
        user.setCreateTime(LocalDateTime.now());
        baseMapper.updateById(user);
        //6.检测完毕后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getUserId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        // 6. 返回登录成功信息
        StudentUserLoginVO loginVO = StudentUserLoginVO.builder()
                .userName(user.getUsername())
                .token(token)
                .role(user.getRole())
                .build();
        return loginVO;
    }

    @Override
    public void register(StudentUserRegisterDTO studentUserRegisterDTO) {
        //1.检测username是否为空
        String username = studentUserRegisterDTO.getUsername();
        if (username.isEmpty()){
             throw new AccountNotFoundException("用户名不能为空");
        }
        //2.检测password是否为空
        String password = studentUserRegisterDTO.getPassword();
        String hashedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (hashedPassword.isEmpty()){
            throw new PasswordErrorException("密码不能为空");
        }
        //3.检测e—mail是否为空
        String email = studentUserRegisterDTO.getEmail();
        if (email.isEmpty()){
            throw new AccountNotFoundException("邮箱不能为空");
        }
        //4.检测phone是否为空
        String phone = studentUserRegisterDTO.getPhone();
        if (phone.isEmpty()){
            throw new AccountNotFoundException("手机号不能为空");
        }
        StudentUser studentUser = new StudentUser();
        BeanUtils.copyProperties(studentUserRegisterDTO,studentUser);
        studentUser.setPassword(hashedPassword);
        baseMapper.insert(studentUser);
        log.info("用户注册成功");
    }

    @Override
    public StudentUserInfoVO info(Integer id) {
        StudentUser studentUser = baseMapper.selectById(id);
        StudentUserInfoVO studentUserInfoVO = new StudentUserInfoVO();
        BeanUtils.copyProperties(studentUser,studentUserInfoVO);
        return studentUserInfoVO;
    }
}
